package org.edu.modules.oa.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.oa.config.HttpURLConnectionUtil;
import org.edu.modules.oa.entity.*;
import org.edu.modules.oa.entity.bo.BasicResponseBO;
import org.edu.modules.oa.mapper.*;
import org.edu.modules.oa.service.IVeOaMeetApplyServer;
import org.edu.modules.oa.vo.VeOaMeetApplyTable;
import org.edu.modules.oa.vo.VeOaMeetCheckTableVo;
import org.edu.modules.oa.vo.VeOaMeetProceedApplyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class VeOaMeetApplyServerImpI implements IVeOaMeetApplyServer {
    @Value("${common.host}")
    private String dirHost ;

    @Autowired
    ObjectMapper mapper;

    @Resource private IVeOaMeetApplyMapper iVeOaMeetApplyMapper;// 会议申请Mapper
    @Resource private IVeOaMeetMapper iVeOaMeetMapper;// 会议Mapper
    @Resource private IVeOaMeetUsersMapper iVeOaMeetUsersMapper;// 会议人员Mapper
    @Resource private IVeOaMeetAttenMapper iVeOaMeetAttenMapper;// 会议考勤Mapper

    @Resource
    private ISysDictItemMapper iSysDictItemMapper; // 字典Mapper

    @Override
    public HashMap<String, Object> showTable(VeOaMeetApplyTable veOaMeetApplyTable, Integer startPage, Integer pageSize) {
        System.out.println(veOaMeetApplyTable);
        // 先拼接一下%%
        veOaMeetApplyTable.setGh("'%"+veOaMeetApplyTable.getGh()+"%'");
        veOaMeetApplyTable.setXm("'%"+veOaMeetApplyTable.getXm()+"%'");
        veOaMeetApplyTable.setSfzjh("'%"+veOaMeetApplyTable.getSfzjh()+"%'");
        veOaMeetApplyTable.setJzglbm("'"+veOaMeetApplyTable.getJzglbm()+"'");
        veOaMeetApplyTable.setBzlbm("'"+veOaMeetApplyTable.getBzlbm()+"'");

        String sql = "where 1=1 ";
        // 进行拼接SQL语句
        if(veOaMeetApplyTable.getGh()!=null && !veOaMeetApplyTable.getGh().equals("'%%'")){
            sql+= " and a.GH like "+veOaMeetApplyTable.getGh();
        }
        if(veOaMeetApplyTable.getXm()!=null && !veOaMeetApplyTable.getXm().equals("'%%'")){
            sql+= " and a.XM like "+veOaMeetApplyTable.getXm();
        }
        if(veOaMeetApplyTable.getSfzjh()!=null && !veOaMeetApplyTable.getSfzjh().equals("'%%'")){
            sql+= " and a.SFZJH like "+veOaMeetApplyTable.getSfzjh();
        }
        if(veOaMeetApplyTable.getJzglbm()!=null && !veOaMeetApplyTable.getJzglbm().equals("''")){
            sql+= " and a.JZGLBM = "+veOaMeetApplyTable.getJzglbm();
        }
        if(veOaMeetApplyTable.getBzlbm()!=null && !veOaMeetApplyTable.getBzlbm().equals("''")){
            sql+= " and a.BZLBM = "+veOaMeetApplyTable.getBzlbm();
        }
        if(veOaMeetApplyTable.getConditionStr()!=null&&!veOaMeetApplyTable.getConditionStr().equals("")){
            String conditionStr[] = veOaMeetApplyTable.getConditionStr().split(",");
                sql+= " and b.id = "+Integer.valueOf(conditionStr[0]);
             if(conditionStr.length>1){
                for (int i=1;i<conditionStr.length;i++){
                    sql+= " or b.id = "+Integer.valueOf(conditionStr[i]) + " ";
                    // 进行拼接SQL语句
                    if(veOaMeetApplyTable.getGh()!=null && !veOaMeetApplyTable.getGh().equals("'%%'")){
                        sql+= " and a.GH like "+veOaMeetApplyTable.getGh();
                    }
                    if(veOaMeetApplyTable.getXm()!=null && !veOaMeetApplyTable.getXm().equals("'%%'")){
                        sql+= " and a.XM like "+veOaMeetApplyTable.getXm();
                    }
                    if(veOaMeetApplyTable.getSfzjh()!=null && !veOaMeetApplyTable.getSfzjh().equals("'%%'")){
                        sql+= " and a.SFZJH like "+veOaMeetApplyTable.getSfzjh();
                    }
                    if(veOaMeetApplyTable.getJzglbm()!=null && !veOaMeetApplyTable.getJzglbm().equals("''")){
                        sql+= " and a.JZGLBM = "+veOaMeetApplyTable.getJzglbm();
                    }
                    if(veOaMeetApplyTable.getBzlbm()!=null && !veOaMeetApplyTable.getBzlbm().equals("''")){
                        sql+= " and a.BZLBM = "+veOaMeetApplyTable.getBzlbm();
                    }

                }

            }

        }
        System.out.println(sql);

        List<VeOaMeetApplyTable> list = iVeOaMeetApplyMapper.showTable((startPage-1)*pageSize,pageSize,sql);

        Integer count = iVeOaMeetApplyMapper.tableCount(sql);

        HashMap<String,Object> map =new   HashMap<String,Object>();
        map.put("list",list);
        map.put("count",count);

        return map;
    }

//    @Override
//    public HashMap<String, Object> showTable(VeOaMeetApplyTable veOaMeetApplyTable, Integer startPage, Integer pageSize) {
//        HashMap<String,Object> map =new   HashMap<String,Object>();
//        String url ="/common/veCommon/getTeacherList?interfaceUserId=09d5e1e7f9b049008eee645c783a1d67";
////        String url ="/common/veCommon/getTeacherPageList?&interfaceUserId=09d5e1e7f9b049008eee645c783a1d67&pageNo=1&pageSize=10";
//        BasicResponseBO<List> list = getUrl(url,List.class);
//        System.out.println(list);
//        List<VeBaseTeacherEntity> result = JSON.parseArray(JSON.toJSONString(list.getResult()),VeBaseTeacherEntity.class);
////        for (int i=0;i<result.size();i++){
////            List<VeOaMeetApplyTable> table = iVeOaMeetApplyMapper.showTable(result.get(i).getJZGLBM(),result.get(i).getBZLBM());
////            System.out.println(table);
////        }
////        List<VeBaseTeacherEntity> date = new ArrayList<>();
////        if(veOaMeetApplyTable.getGh()!=null && !veOaMeetApplyTable.getGh().equals("")){
////            for (int i=0;i<result.size();i++){
////                if (result.get(i).getGH().equals(veOaMeetApplyTable.getGh().trim())){
////                    date.add(result.get(i));
////                }
////            }
////        }else if (veOaMeetApplyTable.getXm()!=null && !veOaMeetApplyTable.getXm().equals("")){
////            for (int i=0;i<result.size();i++){
////                if (result.get(i).getXM().equals(veOaMeetApplyTable.getXm().trim())){
////                    date.add(result.get(i));
////                }
////            }
////        }else if (veOaMeetApplyTable.getSfzjh()!=null && !veOaMeetApplyTable.getSfzjh().equals("")){
////            for (int i=0;i<result.size();i++){
////                if (result.get(i).getSFZJH().equals(veOaMeetApplyTable.getSfzjh().trim())){
////                    date.add(result.get(i));
////                }
////            }
////        }else if (veOaMeetApplyTable.getJzglbm()!=null && !veOaMeetApplyTable.getJzglbm().equals("")){
////            for (int i=0;i<result.size();i++){
////                if (result.get(i).getJZGLBM().equals(veOaMeetApplyTable.getJzglbm().trim())){
////                    date.add(result.get(i));
////                }
////            }
////        }else if (veOaMeetApplyTable.getJzglbm()!=null && !veOaMeetApplyTable.getJzglbm().equals("")){
////            for (int i=0;i<result.size();i++){
////                if (result.get(i).getJZGLBM().equals(veOaMeetApplyTable.getJzglbm().trim())){
////                    date.add(result.get(i));
////                }
////            }
////        }else {
////            date=result;
////        }
//        map.put("list",result);
//        return map;
//    }
    @Transactional
    @Override
    public Integer meetProceedApply(VeOaMeetProceedApplyVo veOaMeetApplyTable) throws Throwable {
        VeOaMeetEntity veOaMeetEntity =new VeOaMeetEntity();
        veOaMeetEntity.setTitle(veOaMeetApplyTable.getTitle());
        veOaMeetEntity.setContent(veOaMeetApplyTable.getContent());
        veOaMeetEntity.setPlaceId(veOaMeetApplyTable.getPlaceId());
        veOaMeetEntity.setContactMan(veOaMeetApplyTable.getContactMan());
        veOaMeetEntity.setMobile(veOaMeetApplyTable.getMobile());
        veOaMeetEntity.setIsDeleted(0);
        veOaMeetEntity.setTerminalId(0);
        Integer count = 0 ;
        // 字符串转换成时间类型
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            veOaMeetEntity.setStartTime(formatter.parse(veOaMeetApplyTable.getStartTime()));
            veOaMeetEntity.setEndTime(formatter.parse(veOaMeetApplyTable.getEndTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaMeetEntity.setUserOut(veOaMeetApplyTable.getUserOut());

        veOaMeetEntity.setCreateBy(user.getId());

        veOaMeetEntity.setAuditUserName(user.getRealname());

           Integer countMeet = iVeOaMeetMapper.insert(veOaMeetEntity);
        Integer countMeetUsers =0;
                Integer countMeetAtten =0;
                String[] confereeData =  veOaMeetApplyTable.getConferee().split(",");
            String[] confereeIdData =  veOaMeetApplyTable.getConfereeId().split(",");
            String str = veOaMeetApplyTable.getConferee()+"&&" + veOaMeetApplyTable.getConfereeId();
//                String[] data =  str.split("&&");
            for(int i=0; i<confereeData.length; i++) {
                VeOaMeetUsersEntity veOaMeetUsersEntity = new VeOaMeetUsersEntity();
                veOaMeetUsersEntity.setMeetId(veOaMeetEntity.getId().intValue());
                veOaMeetUsersEntity.setUserId(confereeIdData[i]);
                veOaMeetUsersEntity.setUserName(confereeData[i]);
                veOaMeetUsersEntity.setCreateBy(user.getId());
                veOaMeetUsersEntity.setUpdateBy(user.getId());
                veOaMeetUsersEntity.setTerminalId(1);
                veOaMeetUsersEntity.setIsSign(0);

                VeOaMeetAttenEntity veOaMeetAttenEntity = new VeOaMeetAttenEntity();
                veOaMeetAttenEntity.setMeetId(veOaMeetEntity.getId().intValue());
                veOaMeetAttenEntity.setMeetName(veOaMeetEntity.getTitle());
                veOaMeetAttenEntity.setUserId(confereeIdData[i]);
                veOaMeetAttenEntity.setUserName(confereeData[i]);
                veOaMeetAttenEntity.setAttenType("1384320144628019202");
                veOaMeetAttenEntity.setAttenName("未到");
                veOaMeetAttenEntity.setTerminalId(1);

                veOaMeetAttenEntity.setCreateBy(user.getId());
                veOaMeetAttenEntity.setCreateName(user.getRealname());
                countMeetUsers+= iVeOaMeetUsersMapper.insert(veOaMeetUsersEntity);
                countMeetAtten+=iVeOaMeetAttenMapper.insert(veOaMeetAttenEntity);
            }

        if(countMeet<=0 ||countMeetUsers<=0||countMeetAtten<=0){
            throw new Throwable();
        }
        count=countMeet+countMeetUsers+countMeetAtten;
//        for (String s : data2) {

//
//            System.out.println(s);
//        }
//        for (String datum : data) {
//            System.out.println(datum);
//        }

        return count;
    }

    @Override
    public HashMap<String, Object> loadBox() {
        QueryWrapper<SysDictItemEntity> staffingWrapper = new QueryWrapper();// 编制类别查询对象
        staffingWrapper.eq("dict_id","1385065789795819522");
        QueryWrapper<SysDictItemEntity> staffWrapper = new QueryWrapper();// 教工类别查询对象
        staffWrapper.eq("dict_id","1385064679441915906");



        List<SysDictItemEntity> staffingList=   iSysDictItemMapper.selectList(staffingWrapper);
        List<SysDictItemEntity> staffList=   iSysDictItemMapper.selectList(staffWrapper);
        HashMap<String,Object> map = new HashMap<>();
        map.put("staffingList",staffingList);
        map.put("staffList",staffList);

        return map;
    }

    /**
     * 调用公告数据接口
     */
    private <T> BasicResponseBO<T> getUrl(String url, Class<T> clazz) {
        try {
            url = dirHost+url ;
            String result = HttpURLConnectionUtil.doGet(url) ;
            BasicResponseBO<T> re = mapper.readValue(result, new TypeReference<BasicResponseBO<T>>() {});
            T body = mapper.readValue(mapper.writeValueAsString(re.getResult()), clazz);
            re.setResult(body);
            return re;
        } catch (Exception e) {
            return new BasicResponseBO<T>().setSuccess(false).setMessage("操作失败");
        }
    }
}
